package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    /**
     * 通过手机验证码快速登录
     *
     * @param map
     * @param resp
     * @return
     */
    @RequestMapping("/login")
    public Result login(@RequestBody Map map, HttpServletResponse resp) {
        //获取页面参数
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从redis获取登录次数
        Jedis resource = jedisPool.getResource();
        String loginCount = resource.get(telephone + RedisMessageConstant.SENDTYPE_LOGINCOUNT);
        if (loginCount != null && Integer.parseInt(loginCount) > 3) {
            //如果登录失败次数超过3次，设置30分钟以后登录
            return new Result(false, MessageConstant.LOGIN_COUNT);
        }
        //从redis获取验证码
        String validateCodeInRedis = resource.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)) {
            if (loginCount != null) {
                //如果登录成功，清除登录失败次数
                resource.srem(telephone + RedisMessageConstant.SENDTYPE_LOGINCOUNT);
                resource.close();
            }
            //验证码校验通过，通过手机号查询会员是否存在
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                //如果不是会员，完成自动注册
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //对手机号加密处理
            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.MINUTE, 30);
            Date tokenOutTime = instance.getTime();
            try {
                String token = DateUtils.parseDate2String(tokenOutTime, "yyyy-MM-dd HH:mm:ss");
                telephone = telephone + "&" + token;
            } catch (Exception e) {
                e.printStackTrace();
            }
            //获取base64编码器
            Base64.Encoder encoder = Base64.getEncoder();
            //编码
            String str = encoder.encodeToString(telephone.getBytes());
            //手机号作为cookie,写入到客户端中
            Cookie cookie = new Cookie("login_member_telephone", str);
            //设置cookie存活时间为30天
            cookie.setMaxAge(60 * 60 * 24 * 30);
            //设置可以获取cookie的路劲
            cookie.setPath("/");
            resp.addCookie(cookie);

            //将会员信息保存到redis中
            String jsonMember = JSON.toJSON(member).toString();
            Jedis resource1 = jedisPool.getResource();
            resource1.setex(telephone, 60 * 60, jsonMember);
            resource1.close();
            //成功返回
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        } else {
            //验证码输入错误，记录失败次数,有效时间为30分钟
            Jedis resource1 = jedisPool.getResource();
            loginCount = resource1.get(telephone + RedisMessageConstant.SENDTYPE_LOGINCOUNT);
            if (loginCount != null) {
                int count = Integer.parseInt(loginCount) + 1;
                resource1.setex(telephone + RedisMessageConstant.SENDTYPE_LOGINCOUNT, 20, count + "");
            } else {
                resource1.setex(telephone + RedisMessageConstant.SENDTYPE_LOGINCOUNT, 20, "1");
            }
            resource1.close();
            //返回错误信息
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    /**
     * 获取登录信息的cookie
     *
     * @param request
     * @return
     */
    public String getCookie(HttpServletRequest request) {
        try {
            //获取所有的cookie ,遍历找出登录存入的cookie
            Cookie[] cookies = request.getCookies();
            if (cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("login_member_telephone")) {
                        String value = cookie.getValue();

                        Base64.Decoder decoder = Base64.getDecoder();
                        byte[] decode = decoder.decode(value);
                        String cookieValue = new String(decode);
                        return cookieValue;
                    }
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据手机号获取会员信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/findByTelephone")
    public Result findByTelephone(HttpServletRequest request) {
        try {
            String cookie = getCookie(request);
            if (cookie != null) {
                String[] split = cookie.split("&");
                String telephone = split[0];
                String regTime = split[1];
                System.out.println("手机号" + telephone + "注册日期" + regTime);
                Member member = memberService.findByTelephone(telephone);
                System.out.println(member);
                return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, member);
            }
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }

    /**
     * 修改会员信息
     *
     * @param member
     * @param request
     * @return
     */
    @RequestMapping("/edit")
    public Result edit(@RequestBody Member member, HttpServletRequest request) {
        System.out.println(member);
        try {
            String idCard = member.getIdCard();
            //根据身份证号获取出生信息
            String year = idCard.substring(6, 10);// 截取年
            String month = idCard.substring(10, 12);// 截取月份
            String day = idCard.substring(12, 14);// 截取天
            String birthday = year + "-" + month + "-" + day+"";   //字符串拼接成生日
            member.setBirthday(DateUtils.parseString2Date(birthday));
            System.out.println(birthday);
            //根据身份证号获取年龄
            Calendar instance = Calendar.getInstance();
            //获取当前系统时间
            String date = String.valueOf(instance.get(Calendar.YEAR));
            System.out.println(date);
            int age = Integer.parseInt(date) - Integer.parseInt(year);
            member.setAge(age);
            System.out.println(age);
            memberService.edit(member);

            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
    }

    /**
     * 根据日期查询预约信息
     *
     * @param startTime
     * @param endTime
     * @param request
     * @return
     */
    @RequestMapping("/findOrderRecord")
    public Result findOrderRecord(String startTime, String endTime, HttpServletRequest request) {
        try {
            List<Map> memberOrder = null;
            //获取参数信息
            Date start = DateUtils.parseString2Date(startTime);   //开始日期
            Date end = DateUtils.parseString2Date(endTime);//结束日期
            System.out.println(start);
            System.out.println(end);
            if (startTime == null || endTime == null) {
                return new Result(false, MessageConstant.GET_ORDERDATE_FAIL);
            }
            //判断开始日期是否大于结束日期
            if (start.before(end)) {
                Result result = findByTelephone(request);
                Member member = (Member) result.getData();
                if (member != null) {

                    Map<String, Object> map = new HashMap<>();
                    map.put("startTime", start);
                    map.put("endTime", end);
                    map.put("memberId", member.getId());
                    memberOrder = memberService.findOrderByDate(map);
                    //判断是否查询到预约信息
                    if (memberOrder.isEmpty()) {
                        return new Result(false, MessageConstant.GET_ORDER_FAIL);
                    }
                    return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, memberOrder);
                } else {
                    return new Result(false, MessageConstant.GET_USERNAME_FAIL);
                }
            } else {
                return new Result(false, MessageConstant.GET_DATE_FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }
}
